//
//  UIView.swift
//  vgbox
//
//  Created by 宋海胜 on 2019/6/25.
//  Copyright © 2019 Swift Xcode. All rights reserved.
//

import Foundation
import RxCocoa
import RxSwift
import Kingfisher

extension UIView{
    
    //UIView的y重置为y
    func resetY(y:CGFloat) ->Void{
        
        var rect:CGRect = self.frame
        var orgin:CGPoint = rect.origin
        orgin.y = y
        rect.origin = orgin
        self.frame = rect
        
    }
    
    //改变view的高度
    func restH(height:CGFloat) ->Void{
        
        var rect:CGRect = self.frame
        var size:CGSize = rect.size
        size.height = height
        rect.size = size
        self.frame = rect
        
    }
    
    class func getWindow()->UIWindow{
        var win:UIWindow? = UIApplication.shared.keyWindow
        
        for item in UIApplication.shared.windows{
            if !item.isHidden{
                win = item
                break
            }
        }
        
        return win!
    }
    
    // 渐变色
    func vg_gradLayerCreat(leftC: UIColor, rightC: UIColor) {
        
        vg_gradLayerCreatWithFrame(frame: self.frame, leftC: leftC, rightC: rightC)
    }
    
    
    func vg_gradLayerCreatWithFrame(frame: CGRect, leftC: UIColor, rightC: UIColor) {
        
        let gradLayer = CAGradientLayer()
        gradLayer.frame = frame
        self.layer.addSublayer(gradLayer)
        gradLayer.colors = [leftC.cgColor, rightC.cgColor]
        let gradLocations: [NSNumber] = [0.0, 1.0]
        gradLayer.locations = gradLocations
        gradLayer.startPoint = CGPoint(x: 0, y: 0)
        gradLayer.endPoint = CGPoint(x: 1, y: 1)
    }
    
    func sy_gradLayerCreat(topC: UIColor, bottomC: UIColor) {
        
        sy_gradLayerCreatWithFrame(frame: self.frame, topC: topC, bottomC: bottomC)
    }
    
    
    func sy_gradLayerCreatWithFrame(frame: CGRect, topC: UIColor, bottomC: UIColor) {
        
        let gradLayer = CAGradientLayer()
        gradLayer.frame = frame
        self.layer.addSublayer(gradLayer)
        gradLayer.colors = [topC.cgColor, bottomC.cgColor]
        let gradLocations: [NSNumber] = [0.0, 1.0]
        gradLayer.locations = gradLocations
        gradLayer.startPoint = CGPoint(x: 0, y: 0)
        gradLayer.endPoint = CGPoint(x: 0, y: 1)
    }
    
    // MARK: 添加渐变色图层
    public func gradientColor(_ startPoint: CGPoint, _ endPoint: CGPoint, _ colors: [Any]) {
        
        guard startPoint.x >= 0, startPoint.x <= 1, startPoint.y >= 0, startPoint.y <= 1, endPoint.x >= 0, endPoint.x <= 1, endPoint.y >= 0, endPoint.y <= 1 else {
            return
        }
        
        // 外界如果改变了self的大小，需要先刷新
        layoutIfNeeded()
        
        var gradientLayer: CAGradientLayer!
        removeGradientLayer()
        gradientLayer = CAGradientLayer()
        gradientLayer.frame = self.layer.bounds
        gradientLayer.startPoint = startPoint
        gradientLayer.endPoint = endPoint
        gradientLayer.colors = colors
        gradientLayer.cornerRadius = self.layer.cornerRadius
        gradientLayer.masksToBounds = true
        // 渐变图层插入到最底层，避免在uibutton上遮盖文字图片
        self.layer.insertSublayer(gradientLayer, at: 0)
        self.backgroundColor = UIColor.clear
        // self如果是UILabel，masksToBounds设为true会导致文字消失
        self.layer.masksToBounds = false
    }
    
    // MARK: 移除渐变图层
    // （当希望只使用backgroundColor的颜色时，需要先移除之前加过的渐变图层）
    public func removeGradientLayer() {
        if let sl = self.layer.sublayers {
            for layer in sl {
                if layer.isKind(of: CAGradientLayer.self) {
                    layer.removeFromSuperlayer()
                }
            }
        }
    }
    
    ///在指定位置添加圆角
    func addCorner(conrners: UIRectCorner , radius: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: conrners, cornerRadii: CGSize(width: radius, height: radius))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
    
    func setupShadow() {
        
        let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 20))
        view.backgroundColor = .white
        view.layer.shadowOffset = CGSize(width: 0, height: -5)
        view.layer.shadowColor = UIColor(r: 0, g: 0, b: 0, a: 0.8).cgColor
        view.layer.shadowOpacity = 0.1
        self.addSubview(view)
    }
    
    /// 将图片转成image
    func creatImg() -> UIImage {
        var s: CGSize = self.bounds.size
        //根据宽高比来截图
        s.width = SCREEN_WIDTH
        s.height = s.width * 667 / 375
        //第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，设置为[UIScreen mainScreen].scale可以保证转成的图片不失真。
        UIGraphicsBeginImageContextWithOptions(s, true, UIScreen.main.scale)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
    
    /// 添加全文
//    func addSeeAllBtn() -> YYLabel {
//        let yylabel: YYLabel = YYLabel()
//        let text = NSMutableAttributedString(string: "... 全文")
//        let hi = YYTextHighlight()
//        text.yy_setColor(UIColor.black, range: (text.string as NSString).range(of: "全文"))
//        text.yy_setTextHighlight(hi, range: (text.string as NSString).range(of: "全文"))
//        text.yy_font = UIFont.systemFont(ofSize: 12)
//        text.yy_setFont(UIFont.boldSystemFont(ofSize: 12), range: (text.string as NSString).range(of: "全文"))
//        let seeMore = YYLabel()
//        seeMore.attributedText = text
//        seeMore.sizeToFit()
//        let truncationToken = NSAttributedString.yy_attachmentString(withContent: seeMore, contentMode: .center, attachmentSize: seeMore.frame.size, alignTo: text.yy_font!, alignment: YYTextVerticalAlignment(rawValue: 0)!)
//        yylabel.truncationToken = truncationToken
//        return yylabel
//    }
    
    /// 部分圆角
    ///
    /// - Parameters:
    ///   - corners: 需要实现为圆角的角，可传入多个
    ///   - radii: 圆角半径
    func corner(byRoundingCorners corners: UIRectCorner, radii: CGFloat) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radii, height: radii))
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
    
    
    /// 绘制圆角
    ///
    /// - Parameters:
    ///   - cornerColor: 圆角及填充颜色
    ///   - bgColor: 区别圆角的背景颜色
    ///   - corners: 圆角位置
    ///   - radii: 圆角值
    func drawCorner(cornerColor:UIColor, bgColor:UIColor, corners: UIRectCorner, radii: CGFloat){
        self.backgroundColor = bgColor
        let cornerRadius:CGFloat = radii
        let bounds:CGRect = self.bounds
        var bezierPath:UIBezierPath?
        bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))
        let layer = CAShapeLayer()
        layer.path = bezierPath?.cgPath
        layer.fillColor = cornerColor.cgColor
        layer.strokeColor = cornerColor.cgColor
        self.layer.insertSublayer(layer, at: 0)
    }
    
    ///添加虚线框 --蓝色
    public func drawDashLine() {
        let shapeLayer:CAShapeLayer = CAShapeLayer()
        
        shapeLayer.bounds = self.bounds
        shapeLayer.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
        
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = UIColor.blue.cgColor
        
        shapeLayer.lineWidth = 1
        shapeLayer.lineJoin = CAShapeLayerLineJoin.round
        shapeLayer.lineDashPhase = 0
        shapeLayer.lineDashPattern = [3,4]
        
        let path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10)
        shapeLayer.path = path.cgPath
        
        
        self.layer.addSublayer(shapeLayer)
    }
    
    /**
     圆角
     使用自动布局，需要在layoutsubviews 中使用
     @param radius 圆角尺寸
     @param corner 圆角位置
     */
//    - (void)acs_radiusWithRadius:(CGFloat)radius corner:(UIRectCorner)corner {
//    if (@available(iOS 11.0, *)) {
//    self.layer.cornerRadius = radius;
//    self.layer.maskedCorners = (CACornerMask)corner;
//    } else {
//    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)];
//    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
//    maskLayer.frame = self.bounds;
//    maskLayer.path = path.CGPath;
//    self.layer.mask = maskLayer;
//    }
//    }
    func vg_radiusWithRadius(radius: CGFloat, corner: UIRectCorner) {
//        if #available(iOS 11.0, *) {
//            self.layer.cornerRadius = radius
//            self.layer.maskedCorners = CACornerMask(rawValue: corner.rawValue)
//        } else {
            let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: radius, height: radius))
            let maskLayer = CAShapeLayer()
            maskLayer.frame = self.bounds
            maskLayer.path = path.cgPath
            self.layer.mask = maskLayer
//        }
    }
    
    
}

extension UIView {
    func addGesture(_ action : (() -> Void)?){
        // 通过objc_setAssociatedObject将闭包保存
        objc_setAssociatedObject(self, &AssociateKeys.vkey , action, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(itemClick(tap:))))
    }
    
    @objc private func itemClick(tap : UITapGestureRecognizer){
        // 点击view，通过objc_getAssociatedObject获取之前保存的闭包并调用
        if let block = objc_getAssociatedObject(self, &AssociateKeys.vkey) as? (()->Void){
            block()
        }
    }
}


extension UIScrollView{
    
    func resetContentsizeH(height:CGFloat) ->Void{
        var size:CGSize = self.contentSize
        size.height = height
        self.contentSize = size
    }
    
    public typealias LTScrollHandle = (UIScrollView) -> Void
    
    private struct LTHandleKey {
        static var key = "glt_handle"
        static var tKey = "glt_isTableViewPlain"
    }
    
    public var scrollHandle: LTScrollHandle? {
        get { return objc_getAssociatedObject(self, &LTHandleKey.key) as? LTScrollHandle }
        set { objc_setAssociatedObject(self, &LTHandleKey.key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) }
    }
    
    @objc public var isTableViewPlain: Bool {
        get { return (objc_getAssociatedObject(self, &LTHandleKey.tKey) as? Bool) ?? false}
        set { objc_setAssociatedObject(self, &LTHandleKey.tKey, newValue, .OBJC_ASSOCIATION_ASSIGN) }
    }
    
    @objc dynamic func glt_scrollViewDidScroll() {
        self.glt_scrollViewDidScroll()
        guard let scrollHandle = scrollHandle else { return }
        scrollHandle(self)
    }
}

extension NSObject {
    
    static func glt_swizzleMethod(_ cls: AnyClass?, _ originSelector: Selector, _ swizzleSelector: Selector)  {
        let originMethod = class_getInstanceMethod(cls, originSelector)
        let swizzleMethod = class_getInstanceMethod(cls, swizzleSelector)
        guard let swMethod = swizzleMethod, let oMethod = originMethod else { return }
        let didAddSuccess: Bool = class_addMethod(cls, originSelector, method_getImplementation(swMethod), method_getTypeEncoding(swMethod))
        if didAddSuccess {
            class_replaceMethod(cls, swizzleSelector, method_getImplementation(oMethod), method_getTypeEncoding(oMethod))
        } else {
            method_exchangeImplementations(oMethod, swMethod)
        }
    }
}


extension UITextField {
    
    var ex_canupsignal:AnyObserver<Bool> {
        
        return UIBindingObserver(UIElement: self) { textfield, valid in
            
            }.asObserver()
    }
}


extension UITableViewCell {
    
    func addlineView() {
        let lineV = UIView()
        lineV.backgroundColor = Constant.lineColor
        self.addSubview(lineV)
        lineV.snp.remakeConstraints { (make) in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(0.5)
        }
    }
    func addLineView(_ left:CGFloat){
        let lineV = UIView()
        lineV.backgroundColor = Constant.lineColor
        self.addSubview(lineV)
        lineV.snp.remakeConstraints { (make) in
            make.left.equalTo(left)
            make.right.bottom.equalTo(0)
            make.height.equalTo(0.5)
        }
    }
}

extension UITableView {
    /*
     弹出一个静态的cell，无须注册重用，例如:
     let cell: GrayLineTableViewCell = tableView.mm_dequeueStaticCell(indexPath)
     即可返回一个类型为GrayLineTableViewCell的对象
     
     - parameter indexPath: cell对应的indexPath
     - returns: 该indexPath对应的cell
     */
    func xq_dequeueStaticCell<T: UITableViewCell>(indexPath: IndexPath) -> T {
        let reuseIdentifier = "staticCellReuseIdentifier - \(indexPath.description)\(arc4random_uniform(10000))"
        if let cell = self.dequeueReusableCell(withIdentifier: reuseIdentifier) as? T {
            return cell
        }else {
            let cell = T(style: .default, reuseIdentifier: reuseIdentifier)
            return cell
        }
    }
    
    func xq_dequeueStaticHeadFoot<T: UITableViewHeaderFooterView>(section: Int) -> T {
        let reuseIdentifier = "staticCellReuseIdentifier - \(section)\(arc4random_uniform(10000))"
        if let cell = self.dequeueReusableHeaderFooterView(withIdentifier: reuseIdentifier) as? T {
            return cell
        }else {
            let view = T(reuseIdentifier: reuseIdentifier)
            return view
        }
    }
}

extension UIPickerView {
    
    /// 隐藏选中的分割线
    func clearSpeartorLine(){
        for (_,view) in subviews.enumerated(){
            if view.frame.size.height < 1 {
                view.backgroundColor = .clear
            }
        }
    }
}
